package com.miaokela.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class FileUploadController {

    @Value("${upload.folder}")
    private String uploadFolder;

    @PostConstruct
    public void init() throws IOException {
        Files.createDirectories(Paths.get(uploadFolder));
    }

    @PostMapping("/upload")
    public ResponseEntity<?> uploadChunk(@RequestParam("file") MultipartFile file,
                                         @RequestParam("chunkIndex") Integer chunkIndex,
                                         @RequestParam("filename") String filename) throws IOException {
        // 构建目标文件的完整路径
        File chunkFile = new File(uploadFolder + filename + "_part_" + chunkIndex).getAbsoluteFile();
        File parentDir = chunkFile.getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdirs(); // 使用绝对路径创建目录及其所有必需的父目录
        }
    
        // 保存文件
        file.transferTo(chunkFile);
        return ResponseEntity.ok().body("{\"message\": \"Chunk uploaded\"}");
    }

    @PostMapping("/merge")
    public ResponseEntity<?> mergeFile(@RequestParam("filename") String filename,
                                       @RequestParam("chunkCount") Integer chunkCount) throws IOException {
        File mergedFile = new File(uploadFolder + filename);
        try (OutputStream mergeFile = new FileOutputStream(mergedFile, true)) {
            for (int i = 0; i < chunkCount; i++) {
                File chunkFile = new File(uploadFolder + filename + "_part_" + i);
                Files.copy(chunkFile.toPath(), mergeFile);
                Files.delete(chunkFile.toPath());
            }
        }
        return ResponseEntity.ok().body("{\"message\": \"File merged\"}");
    }

    @GetMapping("/check")
    public ResponseEntity<?> checkUploaded(@RequestParam("filename") String filename) throws IOException {
        List<Integer> uploadedChunks = new ArrayList<>();
        boolean shouldUpload = true;

        File finalFile = new File(uploadFolder + filename);
        if (finalFile.exists()) {
            shouldUpload = false;
        } else {
            int i = 0;
            while (true) {
                File chunkFile = new File(uploadFolder + filename + "_part_" + i);
                if (chunkFile.exists()) {
                    uploadedChunks.add(i);
                    i++;
                } else {
                    break;
                }
            }
        }

        return ResponseEntity.ok().body("{\"uploadedChunks\":" + uploadedChunks + ", \"shouldUpload\":" + shouldUpload + "}");
    }

}
